package com.wechat.page.api;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.swak.annotation.FluxDepend;
import com.swak.entity.Page;
import com.swak.entity.Parameters;
import com.wechat.command.Command;
import com.wechat.command.Format;
import com.wechat.dto.MessageDTO;
import com.wechat.enums.MessageFlag;
import com.wechat.enums.MessageType;
import com.wechat.login.LoginService;
import com.wechat.service.MessageServiceAsync;
import com.wechat.service.node.NodeService;

/**
 * 消息 -- 请求的中转
 * 
 * @author 618lf
 */
@Service
public class MessageApi {

	@FluxDepend
	private MessageServiceAsync messageService;
	@Autowired
	private NodeService nodeService;

	/**
	 * 准备消息
	 * 
	 * @param chat
	 * @param message
	 * @return
	 */
	public CompletableFuture<MessageDTO> prepare(MessageDTO message) {
		return messageService.prepare(message);
	}

	/**
	 * 发送消息
	 * 
	 * @param message
	 * @return
	 */
	public CompletionStage<MessageDTO> send(MessageDTO message) {

		// 创建命令
		Command command = new Command();
		command.setFrom(LoginService.login().getId());
		command.setTo(message.getTalker());
		command.setCommand(MessageType.of(message.getMsgType()).getCmd());
		command.setFmt(Format.Xml);
		command.setData(message.getMsgContent());

		// 发送命令
		return this.nodeService.send(command).thenCompose(result -> {
			return this.messageService.confirm(message.setMsgFlag(MessageFlag.setSendFlag(message.getMsgFlag(),
					result != null && result.isSuccess() ? MessageFlag.SendSuccess : MessageFlag.SendFail)));
		});
	}

	/**
	 * 查询聊天数据
	 * 
	 * @param query
	 * @param param
	 * @return
	 */
	public CompletableFuture<Page<MessageDTO>> page(MessageDTO query, Parameters param) {
		return messageService.page(query, param.setPageSize(60));
	}
}
